import os
import time
import wxauto
import requests
import pyautogui
import subprocess


def send(sender, key, receiver, subject='subject', body='body', html=None, file=None, fileName='fileName', fileMainType='', fileSubType=''):
    import smtplib
    smtp = smtplib.SMTP('smtp.qq.com', 25)
    import ssl
    context = ssl.create_default_context()
    from email.message import EmailMessage
    msg = EmailMessage()
    msg['subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver
    msg.set_content(body)
    if html is not None:
        msg.add_alternative(html, subtype='html')
    if file is not None and fileMainType is not None and fileSubType is not None:
        msg.add_attachment(file, maintype=fileMainType,
                           subtype=fileSubType, filename=fileName)

    with smtplib.SMTP_SSL("smtp.qq.com", 465, context=context) as smtp:
        smtp.login(sender, key)
        smtp.send_message(msg)


for _ in range(3):
    path = os.path.expanduser("~")+"\\Documents\\WeChat Files\\"
    for dir in os.listdir(path):
        if "wxid_" in dir:
            try:
                os.remove(path+dir+"\\config\\AccInfo.dat")
            except Exception as e:
                print("\033[93m"+str(e)+"\033[0m")
    subprocess.Popen(r'"C:\\Program Files\\Tencent\WeChat\\WeChat.exe"')
    time.sleep(5)
    screenshot = pyautogui.screenshot()
    screenshot.save('qb.png')
    with open('key.txt', 'r') as f:
        key = f.read()
    with open('qb.png', 'rb') as f:
        send("o8oqaqo8o@qq.com", key,
             "1731249586@qq.com", file=f.read(), subject="微信机器人登陆认证", body="扫描文件中二维码登陆微信", fileName="qb.png")
    time.sleep(60)
    try:
        wx = wxauto.WeChat()
        break
    except Exception as e:
        print("\033[93m"+str(e)+"\033[0m")
#### 以上是程序启动后远程微信登陆的准备####
url = "https://gitee.com/guigui1731/pywx/raw/master/"
messages = {}
repMessage = None
repTime = 6  # 自动回复时间从0点持续到repTime
repIndex = 0


def getMessages():
    global messages, repMessage, wx

    repMessage = requests.get(url+'repMessage').text.split('\n')  # 回复语录
    for contact in requests.get(url+'contacts').text.split('\n'):  # 获取有定时任务联系人
        data = requests.get(url+contact).text.split('\n')
        if '::' in data[0]:
            messages[contact] = data
    [wx.AddListenChat(contact) for contact in messages.keys()]


getMessages()
while True:
    current_time = time.localtime()
    if current_time.tm_hour == 23 and current_time.tm_min < 2:  # 定时任务更新时间
        for _ in range(3):
            try:
                getMessages()
                break
            except Exception as e:
                print(e)
        time.sleep(2*60)
    if repIndex != 0 and current_time.tm_hour == repTime:
        repIndex = 0

    for contact in messages.keys():
        for message in messages[contact]:
            message = message.split('::')
            sendTime = message[0].split('.')
            if current_time.tm_hour == int(sendTime[0]) and current_time.tm_min == int(sendTime[1]):
                wx.ChatWith(contact)
                wx.SendMsg(message[1], contact)
        if current_time.tm_hour < repTime and repIndex < len(repMessage):
            data = wx.GetListenMessage()
            if len(data) != 0:
                for newContact in data.keys():
                    if any([message[0] != 'Self' and message[0] != 'Time' and message[0] != 'Sys' for message in data[newContact]]):
                        time.sleep(time.time() % 60)
                        wx.SendMsg(repMessage[repIndex],
                                   newContact.who)  # 如果被监听对象有新消息且不是自己和系统，则选取回复语录语句回复
                        repIndex = repIndex+1

    time.sleep(59)
